package com.viu.technology.chat;

import com.viu.technology.dto.IMMessage;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class NoticeClientHandler extends SimpleChannelInboundHandler {

    private static final Logger log = LoggerFactory.getLogger(NoticeClientHandler.class);

    private int counter;


    static final String ECHO_REQ = "Hi,Lilingfeng. Welcome to Netty.$_";


    public NoticeClientHandler() {

    }


    /**
     * 此处会发生粘包现象，由于TCP会将多条请求消息进行合并再分次发送给服务端
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("开始发送消息");
        IMMessage notice = new IMMessage("成功","数据",1);
        String s = notice.toString()+"$_";
        for (int i = 0; i < 1; i++) {
            ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("This is " + ++counter + " times receive server : [" + msg + "]");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("检测心跳");
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state().equals(IdleState.READER_IDLE)) {
                System.out.println("长期没收到服务器推送数据");
                //可以选择重新连接
            } else if (event.state().equals(IdleState.WRITER_IDLE)) {
                System.out.println("长期未向服务器发送数据");
                //发送心跳包
                //ctx.writeAndFlush(MessageProto.Message.newBuilder().setType(1));
            }else if (event.state().equals(IdleState.ALL_IDLE)) {
                System.out.println("ALL");
            }
        }

    }
}
